/*
 * @Author: heinan
 * @Date: 2023-07-23 22:50:43
 * @Last Modified by: heinan
 * @Last Modified time: 2023-08-09 20:54:44
 */
"use strict";
const { Controller } = require("egg");
const { tokenCreator } = require("../utils");
const svgCaptcha = require("svg-captcha");

/**
 *  @Controller 用户管理
 */
class UserController extends Controller {
  /**
   * @Summary 用户登录
   * @Description 用户、密码、验证码登录
   * @Router POST /user/login
   * @Request body userLogin *body
   */
  async login() {
    try {
      this.ctx.validate({
        captcha: "string",
        username: "string",
        password: "string",
      });
    } catch (err) {
      this.ctx.status = 400;
      return (this.ctx.body = {
        code: 0,
        error: err.errors,
      });
    }
    if (this.ctx.session.captcha !== this.ctx.request.body.captcha) {
      this.ctx.status = 403;
      return (this.ctx.body = {
        code: 0,
        message: "验证码输入错误！",
      });
    }
    const { password, username } = this.ctx.request.body;
    const user = await this.ctx.service.user.find(this.ctx.request.body);
    if (!user) {
      this.ctx.status = 400;
      return (this.ctx.body = {
        code: 0,
        message: `用户:${username}不存在!`,
      });
    }
    if (user.password !== (password)) {
      this.ctx.status = 200;
      return (this.ctx.body = {
        code: 0,
        message: "密码错误!",
      });
    }
    const token = tokenCreator(user.id, "24h");
    this.ctx.status == 200;
    this.ctx.body = {
      code: 1,
      message: "登录成功!",
      id: user.id,
      token,
    };
  }
  /**
   * @Summary 新增用户
   * @Description 用户、密码添加用户
   * @Router POST /user/registry
   * @Request body userRegistry *body
   */
  async registry() {
    try {
      this.ctx.validate({
        username: "string",
        password: "string",
      });
    } catch (err) {
      this.ctx.status = 400;
      return (this.ctx.body = {
        code: 0,
        error: err.errors,
      });
    }
    const { username } = this.ctx.request.body;
    const user = await this.ctx.service.user.find(this.ctx.request.body);
    if (user) {
      this.ctx.status == 400;
      return (this.ctx.body = {
        code: 0,
        msg: `用户: ${username} 已被注册!`,
      });
    }
    const result = await this.ctx.service.user.registry(this.ctx.request.body);
    if (result.affectedRows) {
      this.ctx.body = {
        code: 1,
        msg: "注册成功",
      };
    } else {
      this.ctx.body = {
        code: 0,
        msg: "注册失败",
      };
    }
  }
  /**
   * @summary 获取用户列表
   * @description 分页、多条件查询用户列表
   * @router get /getUserList
   * @request query string nickname 昵称
   * @request query string username 用户名
   * @request query string mobile 手机号
   * @request query Number currentPage 页码 默认 1
   * @request query Number pageSize 单页数量 默认 20
   */
  async getUserList() {
    const result = await this.ctx.service.user.getUserList(this.ctx.query);
    if (result.data.length) {
      this.ctx.body = {
        code: 1,
        msg: "查询成功！",
        ...result,
      };
    } else {
      this.ctx.body = {
        code: 0,
        msg: "暂无数据！",
        data: [],
      };
    }
  }
  /**
   * @Summary 删除用户
   * @Description 用户id删除用户
   * @Router DELETE /user/{id}
   * @Request path string *id
   */
  async destory() {
    const result = await this.ctx.service.user.destory(this.ctx.params);
    if (result.affectedRows) {
      this.ctx.body = {
        code: 1,
        message: "删除成功！",
      };
    } else {
      this.ctx.body = {
        code: 0,
        message: "删除失败！",
      };
    }
  }
  /**
   * @summary 随机验证码
   * @description 登录随机验证码
   * @router GET /user/captcha
   */
  async captcha() {
    var captcha = svgCaptcha.create();
    this.ctx.session.captcha = captcha.text.toLocaleLowerCase();
    this.ctx.response.type = "image/svg+xml";
    this.ctx.body = captcha.data;
  }
  /**
   * @Summary 获取用户身份
   * @Description 根据用户id获取用户身份
   * @Router GET /user/identity/{id}
   * @Request path string *id
   */
  async identity() {
    const result = await this.ctx.service.user.identity(this.ctx.params);
    if (result.length) {
      this.ctx.body = {
        code: 1,
        msg: "查询成功！",
        data: result,
      };
    } else {
      this.ctx.body = {
        code: 0,
        msg: "暂无数据！",
        data: [],
      };
    }
  }
  /**
   * @Summary 忘记密码
   * @Description 根据账号绑定邮箱找回密码
   * @Router post /user/forgot
   * @Request body forgot *body
   */
  async forgot() {
    try {
      this.ctx.validate({
        email: "string",
      });
    } catch (err) {
      this.ctx.status = 400;
      return (this.ctx.body = {
        code: 0,
        error: err.errors,
      });
    }
    const user = await this.ctx.service.user.findEmail(this.ctx.request.body);
    if (!user) {
      this.ctx.status = 403;
      return (this.ctx.body = { code: 0, msg: "该邮箱未注册！" });
    }
    const result = await this.ctx.service.common.email({
      id: user.id,
      ...this.ctx.request.body,
    });
    if (result.response) {
      this.ctx.body = {
        code: 1,
        message: `重置密码邮件已发送到:[${result.accepted}]`,
      };
    } else {
      this.ctx.body = {
        code: 0,
        message: `发送重置密码邮件失败：[${result.rejected}]`,
      };
    }
  }
  /**
   * @Summary 重置密码
   * @Description 根据邮件返回的id重置密码
   * @Router GET /user/reset/${id}
   * @Request path string *id
   * @Request path string password 密码
   */
  async reset() {
    try {
      this.ctx.validate({
        password: "string",
      });
    } catch (err) {
      this.ctx.status = 400;
      return (this.ctx.body = {
        code: 0,
        error: err.errors,
      });
    }
    const result = await this.ctx.service.user.reset({
      ...this.ctx.params,
      ...this.ctx.request.body,
    });
    if (result.affectedRows) {
      this.ctx.body = {
        code: 1,
        message: `重置密码成功！`,
      };
    } else {
      this.ctx.body = {
        code: 0,
        message: "重置密码失败！",
      };
    }
  }

  /**
   * @Summary 查询用户信息
   * @Description 根据用户id查询用户信息
   * @Router GET /user/info/:id
   * @Request path string *id
   */
  async info() {
    const result = await this.ctx.service.user.info(this.ctx.params);
    if (result) {
      this.ctx.body = {
        code: 1,
        msg: "查询成功！",
        data: result,
      };
    } else {
      this.ctx.body = {
        code: 0,
        msg: "暂无数据！",
        data: [],
      };
    }
  }
  /**
   * @Summary 编辑用户信息
   * @Description 根据接口id,接口更新字段
   * @Router PUT /user/info/{id}
   * @Request path string *id
   * @Request body userUpdate *body
   */
  async update() {
    const result = await this.ctx.service.user.update({
      ...this.ctx.params,
      ...this.ctx.request.body,
    });
    if (result.affectedRows) {
      this.ctx.body = {
        code: 1,
        message: "修改成功！",
        ...result,
      };
    } else {
      this.ctx.body = {
        code: 0,
        message: "修改失败！",
      };
    }
  }
  /**
   * @Summary 添加用户信息 (忽略)
   * @Description 根据用户id添加用户信息（登录直接创建用户信息，不需要主动调用！）
   * @Router POST /user/info
   * @Request body userCreate *body
   */
  async add() {
    const result = await this.ctx.service.user.add({
      ...this.ctx.params,
      ...this.ctx.request.body,
    });
    if (result.affectedRows) {
      this.ctx.body = {
        code: 1,
        message: "新增成功成功！",
      };
    } else {
      this.ctx.body = {
        code: 0,
        message: "新增成功失败！",
      };
    }
  }
}

module.exports = UserController;
